//
//  SinaComposeController.swift
//  MySinaWeiBoSwiftProject
//
//  Created by apple on 2016/11/21.
//  Copyright © 2016年 WangChen. All rights reserved.
//

import UIKit
import SVProgressHUD

//定义枚举
enum SinaComposeType: Int {
    case Picture = 10000
    case AtSome
    case Topic
    case Emoticon
    case More
}

private let col: CGFloat = 3
private let picMargin: CGFloat = 8
private let picW: CGFloat = (screenWidth - picMargin * (col + 1)) / col
private let picH: CGFloat = picW


class SinaComposeController: UIViewController {

    let baseTag = 10000
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    //懒加载发布按钮
    lazy var sendBtn: UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        //设置文字
        btn.setTitle("发送", for: .normal)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        //设置文字颜色
        let barButtonItem = UIBarButtonItem(customView: btn)
        barButtonItem.isEnabled = false
        return barButtonItem
    }()

    
    //懒加载文本框
    lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFont(ofSize: 18)
        tv.textColor = UIColor.darkGray
        tv.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
        
        //代理和键盘设置
        tv.delegate = self
        tv.keyboardDismissMode = .onDrag
        tv.alwaysBounceVertical = true
        
        return tv
    }()
    
    
    //懒加载站位Lable
    lazy var placeHolderLable: UILabel = {
        
        let lb = UILabel()
        lb.text = "请在这里输入内容"
        lb.textColor = UIColor.lightGray
        
        return lb
    }()
    
    
    // MARK:
    // MARK: - 懒加载ToolBar
    lazy var toolBar: UIStackView = {
        let bottomBar = UIStackView()
        bottomBar.axis = .horizontal
        bottomBar.distribution = .fillEqually
        return bottomBar
    }()
    
    
    // MARK:
    // MARK: - 懒加载composePictureController
    lazy var pictureVC: SinaComposePictureController = {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: picW, height: picH)
        layout.minimumLineSpacing = picMargin
        layout.minimumInteritemSpacing = picMargin
        layout.sectionInset = UIEdgeInsets(top: picMargin, left: picMargin, bottom: 0, right: picMargin)
        
        let vc = SinaComposePictureController(collectionViewLayout: layout)
        return vc
    }()
    
    
    // MARK:
    // MARK: - 懒加载自定义表情键盘
    lazy var emojiKeyboard = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: 220))
    
    
    // MARK:
    // MARK: - 发布按钮触发
    @objc private func sendBtnDidClick(){
        
        let access_token = SinaUserAccountViewModel.shared.userAccount?.access_token
//        let content = textView.text ?? ""
        
        let paramters = ["access_token":access_token,"status":textView.imageEmoticon2Chs()]
        
        if pictureVC.imageArray.count == 0{
            MyHTTPTools.sharedTool.request(requestMethod: .POST, urlStr: sendWeiboStr, paramters: paramters, finish: {    (responseObj,error) -> () in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发布失败啦")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发布成功啦")
                self.backBtnDidClick()
                return
            })
        }else{
            
            let imageData = UIImagePNGRepresentation(pictureVC.imageArray.first!)
            
            MyHTTPTools.sharedTool.post(sendImageWeiboStr, parameters: paramters, constructingBodyWith: { (formData) in
                formData.appendPart(withFileData: imageData!, name: "pic", fileName: "sasasac", mimeType: "application/octet-stream")
            }, progress: nil, success: { (_, result) in
                SVProgressHUD.showSuccess(withStatus: "图片微博发布成功啦~~")
            }, failure: { (_, error) in
                SVProgressHUD.showError(withStatus: "图片微博发布失败0.0:")
            })
        }
        
        
    }
    
    
    // MARK:
    // MARK: - 把发布的数据进行处理
//    private func dealEmotionText() -> (String){
//        var strM = String()
//        
//        textView.attributedText.enumerateAttributes(in: NSMakeRange(0, textView.attributedText.length), options: []) { (dict, range, stop) in
//            
//            if let attachment = dict["NSAttachment"] as? HMTextAttachment {
//                strM += (attachment.chs ?? "")
//                
//            }else{
//                let subStr = (textView.text as NSString).substring(with: range)
//                strM += subStr
//            }
//            
//            
//        }
//        return strM
//    }
    
    
    
    
    // MARK:
    // MARK: - 界面将要显示的时候
    override func viewWillAppear(_ animated: Bool) {
        pictureVC.view.isHidden = pictureVC.imageArray.count == 0
    }
    
    
    
    // MARK:
    // MARK: - 布局界面
    private func setupUI(){
        self.view.backgroundColor = UIColor.white
        //返回按钮
        setupBackBtn()
        //标题副标题
        setupTitle()
        //发布按钮
        setupComposeBtn()
        //设置文本框
        setupTextView()
        //布局添加图片界面
        setupAddPicture()
        //设置工具条
        setupToolBar()
        //注册通知接收
        registNotification()
        
    }
    
    
    // MARK:
    // MARK: - 布局添加图片界面
    private func setupAddPicture(){
        
        self.view.addSubview(pictureVC.view)
        self.addChildViewController(pictureVC)
        
        pictureVC.view.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(self.view)
            make.top.equalTo(textView.snp.bottom).offset(8)
        }
        
    }
    
    
    
    // MARK:
    // MARK: - 注册通知接收
    private func registNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(changeKeyboardFrame(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //KSelectEmoticon
        NotificationCenter.default.addObserver(self, selector: #selector(insertEmotion(noti:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
        
    }
    
    
    // MARK:
    // MARK: - 通知触发方法
    @objc private func changeKeyboardFrame(notification: Notification){
        let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        
        let offsetY = -(screenHeight - endFrame.origin.y)
        
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(offsetY)
        }
        
        UIView.animate(withDuration: 0.25) {
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    // MARK:
    // MARK: - 表情键盘通知触发方法
    @objc private func insertEmotion(noti: Notification){
        
        let emo = noti.object as? HMEmoticon;
        textView.inputEmoticon(emoticon: emo)
        
    }
    
    
    
    // MARK:
    // MARK: - 输入emotion的方法
//    private func inputEmotion(emotion: HMEmoticon?){
//        guard let em = emotion else {
//            textView.deleteBackward()
//            return
//        }
//        
//        if em.type == 1 {
//            textView.replace(textView.selectedTextRange!, withText: em.emojiStr ?? "")
//        }
//        
//        let attachment = HMTextAttachment()
//        
//        attachment.chs = em.chs
//        
//        let lineHeight = textView.font?.lineHeight
//        
//        attachment.bounds = CGRect(x: 0, y: -4, width: lineHeight!, height: lineHeight!)
//        
//        let bundle = HMEmoticonTools.sharedEmoticonTools.emoticonBundle
//        attachment.image = UIImage(named: em.imagePath!, in: bundle, compatibleWith: nil)
//        
//        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//        
//        //给imageText设置格式
//        imageText.addAttributes([NSFontAttributeName : textView.font!], range: NSMakeRange(0,1))
//        
//        let selRange = textView.selectedRange;
//        //textView的富文本
//        let strM = NSMutableAttributedString(attributedString: textView.attributedText)
//        
//        strM.replaceCharacters(in: textView.selectedRange, with: imageText)
//        
//        textView.attributedText = strM
//     
//        textView.selectedRange = NSMakeRange(selRange.location + 1, 0)
//        
//        //手动调用一下代理方法
//        textView.delegate?.textViewDidChange!(textView)
//    }
    
    
    
    
    // MARK:
    // MARK: - 设置工具条栈视图
    private func setupToolBar(){
        self.view.addSubview(toolBar)
        
        toolBar.snp.makeConstraints { (make) in
            make.trailing.leading.bottom.equalTo(self.view)
            make.height.equalTo(40)
            
        }
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        
        for (index, imageName) in imageNames.enumerated(){
            let btn = UIButton()
            btn.setImage(UIImage.init(named: imageName), for: .normal)
            btn.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
            
            btn.sizeToFit()
            toolBar.addArrangedSubview(btn)
            btn.tag = baseTag + index
            
            btn.addTarget(self, action: #selector(toolBarBtnDidClick(btn:)), for: .touchUpInside)
        }
        
    }
    
    
    // MARK:
    // MARK: - 工具条按钮触发方法
    @objc func toolBarBtnDidClick(btn: UIButton){
        let enumType = SinaComposeType.init(rawValue: btn.tag)!
        switch enumType {
        case .Picture:
            print("选择图片")
            pictureVC.addBtnClick(sender: nil)
            
        case .AtSome:
            print("@某人")
        case .Topic:
            print("话题")
        case .Emoticon:
            print("选择表情")
            
            textView.inputView = textView.inputView == nil ? emojiKeyboard : nil
            
            if !textView.isFirstResponder {
                textView.becomeFirstResponder()
            }
            
            textView.reloadInputViews()
            
        case .More:
            print("更多")
        }
    }
    
    
    
    // MARK:
    // MARK: - 设置文本框
    private func setupTextView(){
        self.view.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.leading.trailing.top.equalTo(self.view)
            make.height.equalTo(screenHeight / 3)
        }
        
        textView.addSubview(placeHolderLable)
        placeHolderLable.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.leading.equalTo(textView).offset(5)
        }
        
    }
    
    
    
    
    // MARK:
    // MARK: - 设置发布按钮
    private func setupComposeBtn(){
        self.navigationItem.rightBarButtonItem = sendBtn
    }
    
    
    
    // MARK:
    // MARK: - 设置标题
    private func setupTitle(){
        let titleLable = UILabel()
        
        titleLable.numberOfLines = 0
        titleLable.textAlignment = .center
        
        if let userName = SinaUserAccountViewModel.shared.userAccount?.name {
            titleLable.text = "发布微博\n\(userName)"
            let range = (titleLable.text! as NSString).range(of: userName)
            
            let strM = NSMutableAttributedString(string: titleLable.text!)
            strM.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 14),NSForegroundColorAttributeName:UIColor.orange], range: range)
            
            titleLable.attributedText = strM
            
        }else{
            titleLable.text = "发布微博"
        }
        
        titleLable.sizeToFit()
        self.navigationItem.titleView = titleLable
        
        
        
    }
    
    
    
    // MARK:
    // MARK: - 设置返回按钮
    private func setupBackBtn(){
        //返回按钮
        let backBtnItem = UIBarButtonItem(title: "返回", imageName: "navigationbar_back_withtext", target: self, action: #selector(backBtnDidClick))
        
        self.navigationItem.leftBarButtonItem = backBtnItem
    }
    
    
    
    // MARK:
    // MARK: - 返回按钮触发
    @objc private func backBtnDidClick(){
        self.dismiss(animated: true, completion: nil)
    }
    

}



extension SinaComposeController: UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        sendBtn.isEnabled = textView.hasText
        placeHolderLable.isHidden = textView.hasText
    }
    
}
